<?php
/**
 * MySQLDatabaseConnection handling MySQL database connection
 * @package Core
 * @subpackage Database
 * @author kovacsricsi
 */
class MySQLDatabaseConnection implements IDatabaseConnection
{
	/**
	 * Connections.
	 * @access protected
	 * @static
     * @staticvar array
	 */
	protected static $_connections = array();

	/**
	 * Constructor protecte the classs, because it is stataic.
	 * @access private
	 * @throws Exception
	 * @return void
	 */
	private function __construct()
	{
		throw new Exception("Illegal operation, this class is only static class!");
	}

	/**
	 * Execute query.
	 * @access public
	 * @static
	 * @param string $query
	 * @param string $name
	 * @throws DatabaseErrorException
	 * @return resource
	 */
	public static function executeQuery($query, $name = "default")
	{
		self::_checkConnection($name);

		$resp = mysql_query($query, self::$_connections[$name]->getConnection());

		if (mysql_errno() != 0) {
			throw new DatabaseErrorException(mysql_error());
		}

		return $resp;
	}

	/**
	 * Protect database from sqlinjection.
	 * @access public
	 * @static
	 * @param string $string
	 * @return string
	 */
    public static function prepare($string)
    {
		self::_checkConnection();

        return (get_magic_quotes_gpc() == true) ? $string : mysql_real_escape_string($string);

    }

	/**
	 * Check for existed connection.
	 * @access protected
	 * @static
	 * @param string $name
	 * @return void
	 */
	protected static function _checkConnection($name = "default")
	{
        if (!isset(self::$_connections[$name]) || !is_resource(self::$_connections[$name]->getConnection())) {
			self::_createConnection($name);
		}
	}

	/**
	 * Create connection.
	 * @access protected
	 * @static
	 * @param string $name
     * @throws DatabaseErrorException
	 * @return void
	 */
	protected static function _createConnection($name = "default")
	{
        $reader = new ConfigReader(DIR_CONFIG . "/MySQL.ini");

		self::$_connections[$name] = new MySQLConnection(mysql_connect($reader->$name->db_host, $reader->$name->db_user, $reader->$name->db_password));

		if (!is_resource(self::$_connections[$name]->getConnection())) {
			throw new DatabaseErrorException($name);
		} else {
			mysql_select_db($reader->$name->db_name, self::$_connections[$name]->getConnection());

			self::executeQuery("SET NAMES " . $reader->$name->db_charset);
		}
	}
}
?>